package cn.cnsy123.blog.application.service.impl;

import cn.cnsy123.blog.application.constants.HttpRequestConstant;
import cn.cnsy123.blog.application.dao.ArticleCommentInfoRepository;
import cn.cnsy123.blog.application.dao.ArticleInfoRepository;
import cn.cnsy123.blog.application.dao.UserDataCountInfoRepository;
import cn.cnsy123.blog.application.dao.UserInfoRepository;
import cn.cnsy123.blog.application.entity.ArticleCommentInfo;
import cn.cnsy123.blog.application.entity.ArticleInfo;
import cn.cnsy123.blog.application.entity.UserDataCountInfo;
import cn.cnsy123.blog.application.entity.UserPersonalInfo;
import cn.cnsy123.blog.application.http.response.*;
import cn.cnsy123.blog.application.service.ArticleQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleQueryServiceImpl  implements ArticleQueryService {

    @Autowired
    private ArticleInfoRepository articleInfoRepository;

    @Autowired
    private ArticleCommentInfoRepository articleCommentInfoRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserDataCountInfoRepository userDataCountInfoRepository;

    @Override
    @Transactional
    public ArticleDetailResponse queryArticle(Long articleId) {
        ArticleDetailResponse articleDetailResponse = new ArticleDetailResponse();
        try {
            Optional<ArticleInfo> optionalArticleInfo = articleInfoRepository.findByDataId(articleId);
            //博文存在
            if(optionalArticleInfo != null && optionalArticleInfo.isPresent()){
                ArticleInfo articleInfo = optionalArticleInfo.get();
                articleDetailResponse.setResultCode("0000");
                articleDetailResponse.setMsg("查询成功");
                //前端显示博文信息
                ArticleResponse articleResponse = new ArticleResponse(articleInfo.getArtileTitle(),
                        articleInfo.getReleaseTime(), articleInfo.getReadCount(),
                        articleInfo.getAppreciateCount(), articleInfo.getArticleLable(),
                        articleInfo.getArticleClassification(),
                        articleInfo.getReprintAddr(), articleInfo.getArticleType(), articleInfo.getArticleContent(),
                        articleInfo.getTopFlag());

                articleDetailResponse.setArticleInfo(articleResponse);

                //评论信息
                List<ArticleCommentInfo> articleCommentInfos = articleCommentInfoRepository.findAllByArticleId(articleId);
                if(articleCommentInfos != null && !articleCommentInfos.isEmpty()){
                    articleDetailResponse.setCommentInfo(convertCommentResponse(articleCommentInfos));
                }

                Optional<UserPersonalInfo> optionalUserPersonalInfo = userInfoRepository.findByUserId(articleInfo.getUserId());
                Optional<UserDataCountInfo> optionalUserDataCountInfo = userDataCountInfoRepository.findByUserId(articleInfo.getUserId());
                if(optionalUserPersonalInfo != null && optionalUserPersonalInfo.isPresent()
                    && optionalUserDataCountInfo != null && optionalUserDataCountInfo.isPresent()){
                    UserPersonalInfo userPersonalInfo = optionalUserPersonalInfo.get();
                    UserDataCountInfo userDataCountInfo = optionalUserDataCountInfo.get();

                    ArticleUserResponse userInfo = new ArticleUserResponse();

                    userInfo.setNickName(userPersonalInfo.getNickName());
                    userInfo.setApproveCount(userDataCountInfo.getApproveCount());
                    userInfo.setCommentCount(userDataCountInfo.getCommentCount());
                    userInfo.setFansCount(userDataCountInfo.getFansCount());
                    userInfo.setOriginalCount(userDataCountInfo.getArticleCount());
                    userInfo.setRankNumber(userDataCountInfo.getRankCount());
                    userInfo.setWeekRankNumber(userDataCountInfo.getWeekRankCount());
                    userInfo.setVisitCount(userDataCountInfo.getVisitCount());

                    articleDetailResponse.setUserInfo(userInfo);
                }



            }else{
                articleDetailResponse.setResultCode("1009");
                articleDetailResponse.setMsg("不存在此博文详细内容");
            }
        }catch (Exception e){
            throw new RuntimeException("查询博文信息出错",e);
        }
        return articleDetailResponse;
    }


    @Override
    public LastArticleResponse queryLastArticleDetail() {
        LastArticleResponse response = new LastArticleResponse();
        Pageable pageable = PageRequest.of(0,5, Sort.by(Sort.Order.desc("releaseTime")));
        Page<ArticleInfo> page = articleInfoRepository.findAll(pageable);
        if(page != null && page.getSize() != 0){
            List<ArticleInfo> list = page.getContent();
            response.setResultCode("0000");
            response.setMsg("查询成功");
            List<SimpleArticleInfo> results = new ArrayList<SimpleArticleInfo>();
            list.forEach(item ->{
                results.add(new SimpleArticleInfo(item.getArtileTitle(),
                        new StringBuffer(HttpRequestConstant.ARTICLE_REQUEST_ADDR).append(item.getDataId()).toString()));
            });
            response.setLastArticleInfo(results);
        }else{
            response = new LastArticleResponse("1002","查无数据");
        }
        return response;
    }

    /**
     * 转换评论信息，显示到前端的字段
     * @param articleCommentInfos
     * @return
     */
    private List<ArticleCommentResponse> convertCommentResponse(List<ArticleCommentInfo> articleCommentInfos){

        List<ArticleCommentResponse> articleCommentResponses = new ArrayList<>();
        articleCommentInfos.forEach(item ->{
            //查询评论者信息
            Optional<UserPersonalInfo> optionalUserPersonalInfo = userInfoRepository.findByUserId(item.getReviewerId());
            if(optionalUserPersonalInfo != null && optionalUserPersonalInfo.isPresent()){
                ArticleCommentResponse articleCommentResponse = new ArticleCommentResponse();
                articleCommentResponse.setCommentContent(item.getCommentContent());
                articleCommentResponse.setCommentTime(item.getCommentTime());
                articleCommentResponse.setReplyCount(0L);
                //获取评论者信息
                UserPersonalInfo userPersonalInfo = optionalUserPersonalInfo.get();
                articleCommentResponse.setNickName(userPersonalInfo.getNickName());
                articleCommentResponses.add(articleCommentResponse);
            }
        });
        return articleCommentResponses;
    }
}
